// packagePay/pages/new-name-sorting/new-name-sorting.js
import {
    queryFontLetter
} from '../../../utils/pinyin'
import {
    getWorkerListGroup,
    setRemark,
    deleteProjectBatchStaff
} from '../../api/pay'
import user from "../../../utils/user"
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        projectId: '',
        active:'',
        letter: ['A', 'B', 'C', 'D', 'E', 'F', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
        isDelete:false,
        isRemarks:false,
        allRadio:false,
        list:[], //页面显示数据
        selects:[],//选中的数据集合
        selectsPay:[], //选中的数据集合三十天未发薪
        selectsRemarks:[], //选中的数据集合备注列表
        selectsInvitee:[], //选中的数据集合邀请人列表
        selectsList:[], //选中的id
        payList:[], // 三十天未发薪列表
        inviteeList:[], // 邀请人列表
        remarksList:[], //邀请人列表
        inviteeNameList: [],
        remarkList: ["这个是个备注"],
        selectInviteeName:'',
        simulationData:[], // 原数据不显示 总数据
        currentInvitee: '',// 当前邀请人
        currentRemarks: '',// 当前备注,
        searchText: '',
        women:'',
        men:'',
        tabList:[
            {
                name:'30天未发薪',
                key:"noPay",
                isChoice:false
            },
            {
                name:'选择邀请人',
                key:"invitee",
                isChoice:false
            },
            {
                name:'选择备注',
                key:"remarks",
                isChoice:false
            }
        ],
        textareaValue:'',
        textLength:8
    },
    onLoad (options) {
        this.setData({
            projectId: options.id
        })
        user.waitLogin().then(()=>{
            this.getWorkerListGroup()
        })
    },
    onReady () {
    },
    onShow () {
        
    },
    async onTabState(event){
        console.log(event,'event')
        const { index } = event.currentTarget.dataset
        console.log(index, 'index')
        this.setData({
            active:this.data.tabList[index].key
        })
        // 选择三十天未发薪
        if(this.data.tabList[index].key === 'noPay'){
            if(!this.data.tabList[index].isChoice){
                this.data.payList.forEach((item,index)=>{
                    if(item.unpaid){
                        this.data.selectsPay.push(item)
                    }
                })
                this.setData({
                    selectsPay:this.data.selectsPay,
                    ['tabList['+ 0 +'].isChoice']: true,
                })
            }else{
                this.setData({
                    selectsPay:[],
                    ['tabList['+ 0 +'].isChoice']: false
                })
            }
            console.log(this.data.selectsPay,'selectsPayselectsPay')
        }
        // 取消筛选 invitee 邀请人
        if(this.data.tabList[index].key === 'invitee') {
            if(this.data.tabList[index].isChoice){
                this.setData({
                    selectsInvitee:[],
                    ['tabList['+ 1 +'].isChoice']: false,
                    currentInvitee:'',
                })
                console.log(this.data.selectsInvitee, '取消选择邀请人')
            }
        }
        // 取消筛选 remarks 备注
        if(this.data.tabList[index].key === 'remarks'){
            if(this.data.tabList[index].isChoice){
                this.setData({
                    selectsRemarks:[],
                    ['tabList['+ 2 +'].isChoice']: false,
                    currentRemarks:'',
                })
                console.log(this.data.selectsRemarks,'selectsRemarks删除')
            }
        }
        await this.onConcatSelects()
        // await this.onConcat()
        // await this.getScreenSelect()
    },
    screenNoPay () {
        console.log('三十天无发薪')
    },
    onGoToLetter(event){
        console.log(event,'event')
        const { letter } = event.currentTarget.dataset
        console.log(event,letter,'event')
    },
    cancel(event){
        this.setData({
            isDelete:false
        })
    },
    // 删除弹窗
    showDeletePopup(){
        if(this.data.selects.length === 0){
            app.toast('请至少选择一个')
            return
        }
        this.setData({
            isDelete:true
        })
    },
    //isRemarks 备注弹窗
    showRemarksPopup(){
        if(this.data.selects.length === 0){
            app.toast('请至少选择一个')
            return
        }
        this.setData({
            isRemarks:true
        })
    },
    // 邀请人筛选
    async onSelectInvitee(event){
        console.log(event, 'event')
        if(event.detail.value){
           this.setData({
               ['tabList['+ 1 +'].isChoice']: true
            })
            this.data.inviteeList.forEach((item,index) => {
                if(this.data.inviteeNameList[event.detail.value] === item.createUserName){
                    this.data.selectsInvitee.push(item)
                }
            })
        }
        await this.onConcatSelects()
        // await this.onConcat()
        // await this.getScreenSelect()
        this.setData({
            selectsInvitee:this.data.selectsInvitee,
            currentInvitee:event.detail.value,
            list:this.initShowWorkers(this.data.simulationData)
        })
        console.log(this.data.selectsInvitee,'selectsInviteeselectsInvitee')
    },
    // 备注筛选
    async onSelectRemark (event) {
        // selectsRemarks:[], //选中的数据集合邀请人列表
        const { value } = event.detail
        if(value){
            console.log('cfa1')
            this.setData({
                ['tabList['+ 2 +'].isChoice']: true
             })
             
             this.data.remarksList.forEach((item,index) => {
                 if(this.data.remarkList[value] === item.remark){
                     this.data.selectsRemarks.push(item)
                 }
             })
         }
         await this.onConcatSelects()
        //  await this.onConcat()
        //  await this.getScreenSelect()
         this.setData({
            selectsRemarks:this.data.selectsRemarks,
            currentRemarks:value
         })
         console.log(this.data.selectsRemarks,'selectsRemarksselectsRemarks')
        console.log(value, '备注筛选')
    },
    async onDelete(){
        const arr = this.data.selects.map(item=>item.id)
        await deleteProjectBatchStaff(arr)
        await this.getWorkerListGroup()
        app.toast('删除成功')
        this.setData({
            selects:[]
        })
        // 重新获取列表
        this.cancel()
    },
    // 取消批量备注
    onCancelRemarks(){
        this.setData({
            isRemarks:false
        })
    },
    async onDetermineRemarks(){
        if(!this.data.textareaValue){
            app.toast('请输入备注')
            return
        }
        if(this.data.textareaValue.length > 8){
            app.toast('备注长度不可大于8')
            return   
        }
        // 编辑接口
        await this.onSetRemark()
        // 关闭弹窗
        await this.onCancelRemarks()
        // 重新获取列表
        await this.getWorkerListGroup()
        // 取消全选
        this.setData({
            selects:[]
        })
    },
    // 编辑接口
    onSetRemark () {
        const arr = this.data.selects.map(item=>item.id)
        setRemark({
            ids:arr,
            remark:this.data.textareaValue
        })
    },
    // 编辑单词input修改
    setTextareaValue(event){
        const { value } = event.detail
        this.setData({
            textareaValue:value
        })
    },
    // 全选
    async onAllRadio(){
        console.log('点击啦')
        if(this.data.selects.length !== this.data.simulationData.length){
            this.data.selects = []
            this.data.selects.push(...this.data.simulationData)
            this.setData({
                selects: this.data.selects
            })
        }
        else{
            this.setData({
                selects: []
            })
        }
        console.log(this.data.selects,'selects')
        // await this.onConcat()
        // await this.getScreenSelect()
    },
    // 单选
    async switchSelect(event){
        const { id } = event.currentTarget.dataset
        console.log(id, 'id')
        console.log(this.data.simulationData,'this.data.simulationData')
        const index = this.data.simulationData.map((item,index)=>{
            if(item.id == id){
                console.log('进入条件判断啦')
                return index
            }else{
                console.log('没进入条件判断')
            }
            
        }).filter(item=>item !== undefined)
        console.log(index,'拿到的下标')
        const worker = this.data.simulationData[index[0]]
        console.log(worker, 'worker')
        const indexed = this.data.selects.indexOf(worker)
        console.log(indexed, 'indexed')
        if(indexed === -1){
            this.data.selects.push(worker)
        }
        else{
            this.data.selects.splice(indexed, 1)
        }
        this.setData({
            selects: this.data.selects
        })
        console.log(this.data.selects,'拿到的数据')
        // await this.onConcatSelects()
        // await this.onConcat()
        // await this.getScreenSelect()
    },
    initShowWorkers(list) {
        // 清洗到字母表中
        const data = {
            length: 0
        }
        for (let letter of this.data.letter) {
            // 增加对象长度字段判断wxml显示
            if (letter === '#') {
                letter = '置顶'
            }
            data[letter] = {
                length: 0
            }
        }
        for (const i in list) {
            // 增加对象长度字段判断wxml显示
            data.length += 1
            // 查询首字母
            const letter = queryFontLetter(list[i].workerName)[0][0]
            data[letter][list[i].id] = list[i]
            data[letter].length += 1
            // if (list[i].isOnTheTop) {
            //     data['置顶'].length += 1
            //     data['置顶'][list[i].id] = list[i]
            // }
        }
        return data
    },
    async searchWorker(event){
        console.log(event, 'event')
        const { value } = event.detail
        this.setData({
            searchText:value
        })
        await this.getWorkerListGroup()
    },
    async getWorkerListGroup () {
        const result = await getWorkerListGroup({
            projectId: this.data.projectId,
            searchText: this.data.searchText
        })
        result.list.forEach((item,index) => {
            result.list[index].encryptionCard = item.idCardNo.substr(14)
            result.list[index].isRadio = false
        })
        
        console.log(result.list, 'result.list')
        
        this.setData({
            women:result.women,
            men:result.men,
            inviteeNameList: result.inviterList,
            remarkList: result.remarkList.length === 0 ? ['暂无备注'] : result.remarkList,
            simulationData: result.list,
            payList:result.list,
            inviteeList:result.list,
            remarksList:result.list,
            list: this.initShowWorkers(result.list)
        })
    },
    onConcat () {
        // 合并到总数据里面
        this.setData({
            list: this.initShowWorkers(Array.from(new Set([...this.data.payList,...this.data.inviteeList,...this.data.remarksList,...this.data.simulationData])))
        })
    },
    // 合并Select集合
    onConcatSelects(){
        this.setData({
            selects:Array.from(new Set([...this.data.selectsPay,...this.data.selectsRemarks,...this.data.selectsInvitee]))
        })
        console.log(this.data.selects,'selects合并后的结果')
    },
    // 该方法每调用一次都会去筛选一遍原数据
    getScreenSelect () {
        const arr = Array.from(this.data.simulationData).map((item,index)=>{
            return item
        }).map(ite=>{
            if(ite.isRadio){
                return ite.id
            }
        }).filter(n=>n)
        this.setData({
            selectsList:arr
        })
        console.log(this.data.selectsList)
    },
    // 去删除人员列表
    goDeletePersonnelList () {
        const arr = this.data.selects.map(item=>item.id)
        wx.navigateTo({
          url: '/packagePay/pages/delete-personnel-list/delete-personnel-list?ids=' + arr,
          events:{
            acceptDataFromOpenedPage:(data)=>{
                console.log(data,'datadatadata')
                this.getWorkerListGroup()
                this.setData({
                    selects:[],
                })
            }
          }
        })
        this.cancel()
    }
})